package com.xiaoyu.client.ui.activity.mall;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.mall.MallGoodsAdapter;
import com.xiaoyu.client.model.goods.GoodsBean;
import com.xiaoyu.client.model.goods.GoodsParam;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.nearby.NearbySearchActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivity;
import com.xiaoyu.commonlib.ui.widget.NestedGridView;
import com.xiaoyu.commonlib.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商城商品搜索页面
 * Created by jk 2018/11/22
 */
public class GoodsSearchActivity extends BaseActivity {

    @BindView(R.id.activity_search_title_back_btn)
    ImageView mBackBtn;//返回
    @BindView(R.id.activity_search_title_search_edit)
    EditText mSearchEdit;//内容编辑框
    @BindView(R.id.activity_search_title_search_btn)
    TextView mCommitBtn;//搜索按钮
    @BindView(R.id.activity_search_no_data_img)
    ImageView nodataImg;//没有数据提示图
    @BindView(R.id.activity_search_grid_list_container)
    GridView mListContainer;//商品列表容器
    @BindView(R.id.activity_search_refresh_layout)
    SmartRefreshLayout mRefreshLayout;//刷新控件

    private MallGoodsAdapter mGoodsAdapter;//产品适配器
    private List<GoodsParam> mGoodsList = new ArrayList<>();
    private int page = 1;//当前页数
    private int totalPage;//总页数
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_search);
        ButterKnife.bind(this);
        mContext = this;
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        mGoodsList.clear();
    }

    private void initView() {
        //商品列表
        mListContainer.setVisibility(View.VISIBLE);
        mGoodsAdapter = new MallGoodsAdapter(this, mGoodsList);
        mListContainer.setAdapter(mGoodsAdapter);
        mListContainer.setOnItemClickListener(onItemClickListener);

        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(true);
        mRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
        mRefreshLayout.setNoMoreData(false);


        mSearchEdit.addTextChangedListener(onTextWatcher);
    }


    //内容编辑框监听
    private TextWatcher onTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
                page = 1;
                mGoodsList.clear();
                mGoodsAdapter.updateList(mGoodsList);
                nodataImg.setVisibility(View.GONE);
            }
        }
    };

    //列表item点击监听
    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(mContext, GoodsDetailsActivity.class);
            intent.putExtra(ClientConstants.GOODS_ID, mGoodsList.get(position).getGoodsid());
            startActivity(intent);
        }
    };

    //加载更多
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage) {
                page = page + 1;
                getGoodsInfo();
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(false);
            } else {
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(true);
                mRefreshLayout.finishLoadMoreWithNoMoreData();
                ToastUtil.showBelowToast(mContext, "已经没有更多数据！！！");
            }
        }
    };


    //返回按钮点击监听
    @OnClick(R.id.activity_search_title_back_btn)
    public void backClick() {
        onBackPressed();
    }


    //搜索按钮点击监听
    @OnClick(R.id.activity_search_title_search_btn)
    public void searchClick() {
        if (TextUtils.isEmpty(mSearchEdit.getText().toString())) {
            ToastUtil.showToast(this, "请输入搜索内容");
            return;
        }
        getGoodsInfo();
    }

    /**
     * 获取商品信息
     */
    private void getGoodsInfo() {
        showLoading();
        NetworkManager.getGoodsByKeyList(page, mSearchEdit.getText().toString(), new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseGoodsInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                ToastUtil.logError("搜索产品", errorCode, errorDiscription);
                dissmissLoading();
            }
        });
    }

    private void parseGoodsInfoSuc(String result) {
        dissmissLoading();
        ToastUtil.logResult("搜索产品", result);
        if (page == 1) {
            mGoodsList.clear();
            mGoodsAdapter.updateList(mGoodsList);
        }
        GoodsBean bean = new Gson().fromJson(result, GoodsBean.class);
        totalPage = Integer.parseInt(bean.getData().getCount());
        mGoodsList.addAll(bean.getData().getList());
        mGoodsAdapter.updateList(mGoodsList);
        nodataImg.setVisibility(View.GONE);
        if (totalPage == 0) {
            nodataImg.setVisibility(View.VISIBLE);
        } else if (totalPage == 1) {
            if (mGoodsList.size() == 0) {
                nodataImg.setVisibility(View.VISIBLE);
            }
            mRefreshLayout.setEnableLoadMore(false);
        } else {
            mRefreshLayout.setEnableLoadMore(true);
        }
    }
}
